<template>
  <div class="carriage-management">
    <div class="header">
      <h2>车厢管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        添加车厢
      </el-button>
    </div>

    <!-- 车次选择器 -->
    <div class="filter-area">
      <el-form :model="filterForm" inline>
        <el-form-item label="选择车次">
          <el-select 
            v-model="filterForm.trainId" 
            placeholder="选择车次"
            @change="handleTrainChange"
            clearable
            filterable
          >
            <el-option
              v-for="train in trains"
              :key="train.id"
              :label="`${train.trainNumber} (${train.startStationName} → ${train.endStationName})`"
              :value="train.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="carriages" border style="width: 100%">
      <el-table-column prop="carriageNumber" label="车厢号" width="100" sortable />
      <el-table-column label="车厢类型" width="120">
        <template #default="{ row }">
          <el-tag>{{ getCarriageTypeLabel(row.carriageType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="totalSeats" label="总座位数" width="120" />
      <el-table-column prop="availableSeats" label="可用座位" width="120">
        <template #default="{ row }">
          <el-tag 
            :type="row.availableSeats > 0 ? 'success' : 'danger'"
          >
            {{ row.availableSeats }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="trainNumber" label="车次号" width="120" />
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button size="small" @click="viewSeats(row)">
            查看座位
          </el-button>
          <el-button size="small" @click="editCarriage(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteCarriage(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑车厢对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑车厢' : '添加车厢'"
      width="500px"
    >
      <el-form :model="carriageForm" :rules="rules" ref="carriageFormRef" label-width="100px">
        <el-form-item label="车次" prop="trainId">
          <el-select v-model="carriageForm.trainId" placeholder="请选择车次">
            <el-option
              v-for="train in trains"
              :key="train.id"
              :label="`${train.trainNumber} (${train.startStationName} → ${train.endStationName})`"
              :value="train.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="车厢号" prop="carriageNumber">
          <el-input-number 
            v-model="carriageForm.carriageNumber" 
            :min="1" 
            :max="20"
            placeholder="请输入车厢号" 
          />
        </el-form-item>
        
        <el-form-item label="车厢类型" prop="carriageType">
          <el-select v-model="carriageForm.carriageType" placeholder="请选择车厢类型">
            <el-option
              v-for="type in CARRIAGE_TYPES"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="座位总数" prop="totalSeats">
          <el-input-number 
            v-model="carriageForm.totalSeats" 
            :min="10" 
            :max="100"
            placeholder="请输入座位总数" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCarriage">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 座位查看对话框 -->
    <el-dialog v-model="seatDialogVisible" title="座位信息" width="80%">
      <seat-grid 
        v-if="selectedCarriage" 
        :carriage="selectedCarriage"
        @refresh="fetchCarriages"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { carriageApi, trainApi } from '@/api/train'
import { CARRIAGE_TYPES, CARRIAGE_TYPE_MAP } from '@/constants/train'
import type { Carriage, Train, CarriageType, CreateCarriageRequest } from '@/types/train'
import SeatGrid from './components/SeatGrid.vue'

const carriages = ref<Carriage[]>([])
const trains = ref<Train[]>([])
const dialogVisible = ref(false)
const seatDialogVisible = ref(false)
const isEdit = ref(false)
const carriageFormRef = ref()
const selectedCarriage = ref<Carriage | null>(null)

const filterForm = reactive({
  trainId: null as number | null
})

const carriageForm = reactive({
  id: null as number | null,
  trainId: null as number | null,
  carriageNumber: 1,
  carriageType: '' as CarriageType,
  totalSeats: 50
})

const rules = {
  trainId: [
    { required: true, message: '请选择车次', trigger: 'change' }
  ],
  carriageNumber: [
    { required: true, message: '请输入车厢号', trigger: 'blur' }
  ],
  carriageType: [
    { required: true, message: '请选择车厢类型', trigger: 'change' }
  ],
  totalSeats: [
    { required: true, message: '请输入座位总数', trigger: 'blur' }
  ]
}

// 获取车厢列表
const fetchCarriages = async () => {
  try {
    let response
    if (filterForm.trainId) {
      response = await carriageApi.getCarriagesByTrainId(filterForm.trainId)
    } else {
      response = await carriageApi.getAllCarriages()
    }
    
    if (response.success) {
      carriages.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取车厢列表失败:', error)
    ElMessage.error('获取车厢列表失败')
  }
}

// 获取车次列表
const fetchTrains = async () => {
  try {
    const response = await trainApi.getAllTrains()
    if (response.success) {
      trains.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取车次列表失败:', error)
    ElMessage.error('获取车次列表失败')
  }
}

// 车次选择变化
const handleTrainChange = () => {
  fetchCarriages()
}

// 显示创建对话框
const showCreateDialog = () => {
  resetForm()
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑车厢
const editCarriage = (carriage: Carriage) => {
  Object.assign(carriageForm, carriage)
  isEdit.value = true
  dialogVisible.value = true
}

// 查看座位
const viewSeats = (carriage: Carriage) => {
  selectedCarriage.value = carriage
  seatDialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(carriageForm, {
    id: null,
    trainId: filterForm.trainId || null,
    carriageNumber: 1,
    carriageType: '' as CarriageType,
    totalSeats: 50
  })
  carriageFormRef.value?.clearValidate()
}

// 保存车厢
const saveCarriage = async () => {
  try {
    const valid = await carriageFormRef.value.validate()
    if (!valid) return
    
    const requestData: CreateCarriageRequest = {
      trainId: carriageForm.trainId!,
      carriageNumber: carriageForm.carriageNumber,
      carriageType: carriageForm.carriageType,
      totalSeats: carriageForm.totalSeats
    }
    
    let response
    if (isEdit.value) {
      response = await carriageApi.updateCarriage(carriageForm.id!, requestData)
    } else {
      response = await carriageApi.createCarriage(requestData)
    }
    
    if (response.success) {
      ElMessage.success(response.message)
      dialogVisible.value = false
      fetchCarriages()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error(isEdit.value ? '更新车厢失败' : '创建车厢失败', error)
    ElMessage.error(isEdit.value ? '更新车厢失败' : '创建车厢失败')
  }
}

// 删除车厢
const deleteCarriage = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个车厢吗？这将同时删除该车厢的所有座位！', '确认删除', {
      type: 'warning'
    })
    
    const response = await carriageApi.deleteCarriage(id)
    if (response.success) {
      ElMessage.success(response.message)
      fetchCarriages()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除车厢失败:', error)
      ElMessage.error('删除车厢失败')
    }
  }
}

// 获取车厢类型标签
const getCarriageTypeLabel = (type: CarriageType) => {
  return CARRIAGE_TYPE_MAP[type] || type
}

onMounted(() => {
  fetchTrains()
  fetchCarriages() // 默认加载所有车厢
})
</script>

<style scoped>
.carriage-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.filter-area {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}
</style>